<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class Machine extends Resource
{
    protected $params = [];
    
    private static $fetchKeys = [
        'id', 'name', 'ware_name', 'room_id', 'device_status', 'game_mode',
        'coin', 'ware_image'
    ];
    
    public function __construct($resource, $params = [])
    {
        parent::__construct($resource);
        
        $this->params = $params;
    }
    
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        /** @var \App\Models\Machine $machine */
        $machine = $this->resource;
        
        $item = object_only($machine, self::$fetchKeys);

        $item['detail_image'] = image_url($machine->detail_image);
        $item['cameras'] = $this->cameras($machine);
        $item['player'] = $this->whenLoaded('latestUser', function () use ($machine) {
            return $this->player($machine);
        });
        
        // 排队人数
        if (isset($this->params['queue_length'])) {
            $item['queue_length'] = $this->params['queue_length'];
        }
        
        if (doll_video_scheme('qcloud')) {
            $item['room_id'] = intval($item['room_id']);
            $item['qcloud_sig'] = $machine->getQCloudSig();
        }
        
        return $item;
    }
    
    /**
     * 摄像头数据
     *
     * @param \App\Models\Machine $machine
     * @return array
     */
    public function cameras($machine)
    {
        return $machine->cameras->map(function ($camera) {
            /** @var \App\Models\Camera $camera */
            
            return $camera->attributesToArray();
        })->all();
    }
    
    /**
     * 玩家信息
     *
     * @param \App\Models\Machine $machine
     * @return array|null
     */
    public function player($machine)
    {
        if (! $machine->isWorking()) {
            return;
        }
        
        $user = $machine->latestUser;
        return [
            'avatar' => image_url($user->avatar),
            'nickname' => $user->nickname,
        ];
    }
}
